<template>
  <div class="app">
    <div class="wechat-container">
      <!-- 左侧导航栏 -->
      <div class="sidebar">
        <div class="nav-item active">
          <el-avatar shape="square" class="fas"
            src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"></el-avatar>
        </div>
        <div>
          <div>
            <div class="nav-item" @click="getTopicId()">
              <i class="fas el-icon-chat-round"></i>
            </div>
            <div class="nav-item">
              <i class="fas el-icon-user"></i>
            </div>
          </div>
          <div class="set-item">
            <div class="nav-item">
              <i class="fas el-icon-setting"></i>
            </div>
            <div class="nav-item">
              <i class="fas el-icon-lock"></i>
            </div>
          </div>
        </div>
      </div>
      <!-- 左侧联系人列表 -->
      <div class="contact-panel">
        <div class="search-bar">
          <div class="search-box">
            <i class="fas el-icon-search"></i>
            <input type="text" placeholder="搜索" v-model="topicInput">
          </div>
          <div class="search-add" @click="addTopic()">
            <el-tag color="#e6e6e6" type="info"><i class="fas el-icon-plus"></i></el-tag>
          </div>
        </div>
        <div class="contact-list">
          <div class="contact-item active" v-for="item in chats">
            <div class="contact-avatar ">
              <el-avatar shape="square" class="fas" :src="item.avatar"></el-avatar>
            </div>
            <div class="contact-info">
              <div class="contact-name">{{ item.name }}</div>
              <div class="contact-preview">{{ item.lastMsg }}</div>
            </div>
            <div class="contact-meta">
              <div class="contact-time">{{ item.lastTime }}</div>
              <div class="unread-count " :class="item.unreadCount == 0 ? '' : 'not-count'"> {{ item.unreadCount ==
              0
              ?
              "" : item.unreadCount }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧聊天区域 -->
      <div class="chat-container">
        <div class="chat-header">
          <div class="chat-title">
            <div class="chat-avatar ">
              <el-avatar shape="square" class="fas"
                src="https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80"></el-avatar>
            </div>
            <div>
              <div class="chat-name">李四</div>
              <!-- <div class="chat-status">在线</div> -->
            </div>
          </div>
          <div class="chat-actions">
            <div class="nav-item">
              <i class="fas el-icon-more"></i>
            </div>
          </div>
        </div>
        <div class="chat-messages" ref="contentRef">
          <div v-for="item in dialogueChat">
            <div v-if="item.messageType == 'message-other'" class="timestamp">13:14</div>
            <div v-if="item.messageType == 'message-other'" class="message other">
              <div class="message-avatar">
                <el-avatar shape="square" class="fas" :src="item.chatAvatar"></el-avatar>
              </div>
              <div class="message-content">
                <div class="message-bubble">
                  {{ item.messageBubble }}
                </div>
                <!-- <div class="message-time">{{ item.timestamp }}</div> -->
              </div>
            </div>
            <div v-if="item.messageType == 'message-self'" class="message self">
              <div class="message-avatar">
                <el-avatar shape="square" class="fas" :src="item.chatAvatar"></el-avatar>
              </div>
              <div class="message-content">
                <div class="message-bubble">
                  {{ item.messageBubble }}
                </div>
                <!-- <div class="message-time">{{ item.timestamp }}</div> -->
              </div>
            </div>
          </div>

        </div>
        <div class="chat-input-area">
          <div class="input-tools">
            <div class="tool-btn">
              <i class="far el-icon-picture-outline"></i>
            </div>
            <div class="tool-btn">
              <i class="far el-icon-video-camera"></i>
            </div>
          </div>
          <textarea v-model="messageInput" class="message-input" placeholder="输入消息..."></textarea>
          <div class="input-actions">
            <button class="send-btn" @click="sendMessage()">发送</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script lang="ts" setup>
import { ref, nextTick, onMounted } from 'vue'
import mqtt from "mqtt";

const personId = JSON.parse(localStorage.getItem("userLoginInfo"))
const contentRef = ref(null);
const chats = ref([
  {
    id: 1,
    name: '技术交流群',
    avatar: 'https://images.unsplash.com/photo-1568992688065-536aad8a12f6?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
    lastMsg: '大家对这个方案有什么建议？',
    lastMsgType: 'text',
    lastTime: '09:45',
    unreadCount: 12,
  },
  {
    id: 2,
    name: '李四',
    avatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
    lastMsg: '我昨天拍的照片，你觉得怎么样？',
    lastMsgType: 'image',
    lastTime: '09:30',
    unreadCount: 0,
  },
])

const topic = ref('test')
const topicInput = ref('')
const messageInput = ref('');
let client = null;

const dialogueChat = ref([])
// const dialogueChat = ref([
//   {
//     messageType: 'message-other',
//     messageBubble: 'Will us to buy a baby...',
//     timestamp: '13:14',
//     chatAvatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
//   }, {
//     messageType: 'message-self',
//     messageBubble: 'Are you kidding me?',
//     timestamp: '13:15',
//     chatAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
//   }
// ])
const addTopic = () => {
  topic.value = topicInput.value;
  client.subscribe(topic.value, (err) => {
    if (!err) {
      console.log("手动订阅成功 ", topic.value);
    }
  });
  topicInput.value = "";
}
const sendMessage = () => {
  console.log('发消息...')
  if (messageInput.value === null || messageInput.value === '') {
    return;
  }
  message.value = messageInput.value;
  publishMessage()

  dialogueChat.value.push({
    messageType: 'message-self',
    messageBubble: messageInput.value,
    timestamp: '13:15',
    chatAvatar: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
  })

  nextTick(() => {
    contentRef.value.scrollTop = contentRef.value.scrollHeight;
  });

  messageInput.value = '';
}

const connected = ref(false);
const message = ref("");
const receivedMessages = ref([]);


//获取Mqtt订阅主题
const getTopicId = async () => {
  //主题根据mqtt服务器订阅的
  connect();
}

const connect = () => {
  // 连接 MQTT Broker (WebSocket)
  let wsUrl = import.meta.env.VITE_APP_WEBSOCKET_URL || 'ws://127.0.0.1:8033'
  client = mqtt.connect(wsUrl, {
    clientId: "vue3_" + Math.random().toString(16).substr(2, 8),
    clean: true,
    connectTimeout: 4000,
    username: "", // 如果启用了认证，就填账号
    password: "",
  });

  client.on("connect", () => {
    connected.value = true;
    console.log("已连接 MQTT");

    // 订阅主题
    client.subscribe("test/topic", (err) => {
      if (!err) {
        topic.value = "test/topic";
        console.log("订阅成功 test/topic");
      }
    });
  });
  client.on("message", (topic, payload) => {
    console.log("收到消息:", topic, payload.toString())
    let recvMsg = JSON.parse(payload.toString())
    if (recvMsg === null || recvMsg === '' || recvMsg.id === personId.user.id) {
      return;
    }
    dialogueChat.value.push(
      {
        messageType: 'message-other',
        messageBubble: recvMsg.msg,
        timestamp: '13:14',
        chatAvatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
      }
    )
    nextTick(() => {
      contentRef.value.scrollTop = contentRef.value.scrollHeight;
    });
  });

  client.on("error", (err) => {
    console.error("连接错误:", err);
  });

  client.on("close", () => {
    connected.value = false;
    console.log("连接关闭");
  });
};

const publishMessage = () => {
  if (client && connected.value) {
    console.log("personId:", personId.user.id);
    let sendMessage = {
      id: personId.user.id,
      msg: message.value,
    }
    client.publish(topic.value, JSON.stringify(sendMessage));
    message.value = "";
  }
};
onMounted(() => {
  connect()
})
</script>

<style scoped>
* {
  margin: 0;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
}



.app {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  min-height: 90vh;
  overflow-x: auto;
  padding: 20px;
}

.wechat-container {
  display: flex;
  min-width: 800px;
  width: 100%;
  max-width: 1200px;
  height: 700px;
  background-color: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  position: relative;
}

/* 左侧导航栏 */
.sidebar {
  width: 65px;

  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 0;

}

.nav-item {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  cursor: pointer;
  color: #7d7d7d;
  transition: all 0.2s;
  position: relative;
}

.set-item {
  width: 100%;
  position: absolute;
  bottom: 0;
}

.nav-item.active {
  color: #07C160;
}

.nav-item:hover:not(.active) {
  background-color: #dad6d6;
}

.nav-item i {
  font-size: 20px;
}


/* 左侧联系人列表 */
.contact-panel {
  width: 230px;
  border-right: 1px solid #d8d8d8;
  display: flex;
  flex-direction: column;
}

.search-bar {
  background: #fbfbfb;
  padding: 15px 10px;
  display: flex;
  align-items: center;
}

.search-box {
  background-color: #e6e6e6;
  border-radius: 4px;
  padding: 1px 12px;
  display: flex;
  align-items: center;
  position: relative;
}

.search-add {
  margin-left: 10px;
}

.search-box i {
  color: #9b9b9b;
  font-size: 14px;
  margin-right: 6px;
}

.search-box input {
  background: transparent;
  border: none;
  color: #333;
  width: 100%;
  outline: none;
  font-size: 12px;
  padding: 4px 0;
}

.search-box input::placeholder {
  color: #9b9b9b;
}

.contact-list {
  flex: 1;
  overflow-y: auto;
  background-color: #fbfbfb;
}

.contact-item {
  display: flex;
  height: 65px;
  align-items: center;
  padding: 10px 15px;
  cursor: pointer;

}

.contact-item:hover {
  background-color: #f5f5f5;
}

.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  position: relative;
}

.contact-avatar.online::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  background-color: #07C160;
  border: 2px solid white;
  border-radius: 50%;
}

.contact-info {
  flex: 1;
  min-width: 0;
  text-align: left;
  /* 确保文本左对齐 */
  overflow: hidden;
  /* 防止内容溢出 */
}

.contact-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
  /* 确保左对齐 */
}

.contact-preview {
  font-size: 12px;
  color: #7d7d7d;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
  /* 确保左对齐 */
}

.contact-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  flex-shrink: 0;
}

.contact-time {
  font-size: 11px;
  color: #9b9b9b;
  margin-bottom: 4px;
}

.unread-count {
  color: white;
  font-size: 11px;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.not-count {
  background-color: #f56c6c;
}

/* 右侧聊天区域 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f0f0;
}

.chat-header {
  padding: 12px 16px;
  background-color: #ededed;
  border-bottom: 1px solid #d4d4d4;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-title {
  display: flex;
  align-items: center;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  position: relative;
}

.chat-avatar.online::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  background-color: #07C160;
  border: 2px solid white;
  border-radius: 50%;
}

.chat-name {
  font-weight: 500;
  font-size: 16px;
  color: #333;
}

.chat-status {
  font-size: 12px;
  color: #9b9b9b;
  margin-top: 2px;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.message.self {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  margin: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.message-content {
  max-width: 65%;
  position: relative;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message.other .message-bubble {
  background-color: #ffffff;
  border: 1px solid #e6e6e6;
  margin-left: 10px;
}

.message.other .message-bubble::before {
  content: "";
  position: absolute;
  left: -8px;
  top: 12px;
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 8px solid #ffffff;
}

.message.self .message-bubble {
  background-color: #9eea6a;
  color: #333;
  margin-right: 10px;
}

.message.self .message-bubble::after {
  content: "";
  position: absolute;
  right: -8px;
  top: 12px;
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-left: 8px solid #9eea6a;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: center;
}

.message.self .message-time {
  text-align: right;
  padding-right: 15px;
}

.message.other .message-time {
  text-align: left;
  padding-left: 15px;
}

.timestamp {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 15px 0;
}

.chat-input-area {
  padding: 15px;
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
  position: relative;
}

.input-tools {
  display: flex;
  padding: 5px 0;
  margin-bottom: 10px;
}

.tool-btn {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #7d7d7d;
  cursor: pointer;
  margin-right: 8px;
  transition: all 0.2s;
}

.tool-btn:hover {
  background-color: #e0e0e0;
  color: #333;
}

.message-input {
  width: 100%;
  height: 100px;
  padding: 12px;

  resize: none;
  font-size: 14px;
  transition: border-color 0.2s;
  border: none;
  /* 去除边框 */
  background: none;
  /* 去除背景颜色 */
  outline: none;
}

.message-input:focus {
  border-color: #07C160;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.send-btn {
  padding: 5px 30px;
  background-color: #07C160;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-btn:hover {
  background-color: #06ad56;
}

.send-btn:active {
  background-color: #059a4c;
}
</style>
